package cn.shop.gateway.view;

import cn.hutool.core.util.StrUtil;
import cn.shop.gateway.MainApp;
import cn.shop.gateway.db.DbUtil;
import cn.shop.gateway.http.ApiUtil;
import cn.shop.gateway.model.MerchantUser;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * @author : 李一涵
 * @date : Created in 2021-12-7 15:33
 * @description :
 */
public class LoginController {
    private final static Logger LOG = LoggerFactory.getLogger(LoginController.class);

    @FXML
    private TextField accountField;
    @FXML
    private PasswordField passwordField;
    @FXML
    private Label alert;

    private Stage loginStage;
    private MainApp app;

    public void setLoginStage(Stage loginStage) {
        this.loginStage = loginStage;
    }
    public void setApp(MainApp app) {
        this.app = app;
    }

    @FXML
    private void initialize() {
        accountField.setOnInputMethodTextChanged(event -> alert.setText(""));
        passwordField.setOnInputMethodTextChanged(event -> alert.setText(""));
    }


    @FXML
    public void auth() throws IOException {
        String account = accountField.getText();
        String password = passwordField.getText();
        if (StrUtil.isBlank(account)) {
            alert.setText("请输入用户名");
            return;
        }
        if (StrUtil.isBlank(password)) {
            alert.setText("请输入密码");
            return;
        }
        MerchantUser user = null;
        try {
            user = ApiUtil.auth(account, password);
        } catch (Exception e) {
            LOG.error("验证出错", e);
            alert.setText("系统出错");
            return;
        }
        if (user == null) {
            alert.setText("请检查用户名和密码");
            return;
        }
        try {
            DbUtil.insertMerchantInfo(user);
            if (user.getSecret() != null && !user.getSecret().isEmpty()) {
                DbUtil.saveSecret(user.getSecret());
            }
        } catch (Exception e) {
            LOG.error("验证成功插入出错", e);
            alert.setText("系统出错");
            return;
        }
        loginStage.close();
        app.showSelectTemplate(user.getId());
    }

}
